package com.hmall.es;

import com.alibaba.fastjson.JSON;
import com.hmall.common.client.ItemFeignClient;
import com.hmall.common.dto.ItemDto;
import com.hmall.common.dto.PageResult;
import com.hmall.es.pojo.ItemDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.List;

@SpringBootTest
@RunWith(SpringRunner.class)
public class EsImport {

    @Autowired
    private ItemFeignClient itemFeignClient;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 批量导入数据到es中的操作
     */
    @Test
    public void importItemToEs() throws IOException {
        Integer page=1;
        while (true){
            //1.获取mysql中的商品 数据，8万多条
            PageResult<ItemDto>pageResult = itemFeignClient.list(page, 10);
            //2获取商品信息
            List<ItemDto>list = pageResult.getList();
            if(list.size()<=0){
                break;
            }
            //2.分页导入到ES

            //4创建批量请求对象
            BulkRequest bulkRequest=new BulkRequest();

            for (ItemDto itemDto : list) {

                if(itemDto.getStatus()==2){
                    continue;
                }

                //类型转换
                ItemDoc itemDoc=new ItemDoc(itemDto);
                String source= JSON.toJSONString(itemDoc);

                //6创建索引请求对象,并指定索引名称，
                IndexRequest indexRequest=new IndexRequest("hmall").id(itemDoc.getId().toString());
                //7往索引对象中添加数据，数据类型指定的是json
                indexRequest.source(source, XContentType.JSON);
                //5往批量请求对象中添加参数
                bulkRequest.add(indexRequest);
            }

            //3调用批量导入方法
            client.bulk(bulkRequest, RequestOptions.DEFAULT);

            page++;
        }
    }
}
